﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public static class AssetHelper
{
    public static T[] GetPrefab<T>()where T:UnityEngine.Object
    {
        var files = Directory.GetFiles(Application.dataPath, "*.*", SearchOption.AllDirectories)
                    .Where(s => ".prefab".Contains(Path.GetExtension(s).ToLower())).ToArray();

        List<UnityEngine.Object> list = new List<UnityEngine.Object>();
        foreach (var file in files)
        {
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(file.Substring(file.IndexOf("Assets")));
            list.Add(prefab);
        }

        Selection.objects = list.ToArray();
        var array = Resources.FindObjectsOfTypeAll<GameObject>();
        List<T> result = new List<T>();
        foreach (var item in array)
        {
            if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(item)))
                continue;
            var com = item.GetComponent<T>();
            if (com == null)
                continue;
            result.Add(com);
        }
        Selection.objects = new UnityEngine.Object[] { };
        return result.ToArray();
    }

    public static T[] GetHierachy<T>()where T:UnityEngine.Object
    {
        List<T> result = new List<T>();

        var allGos = Resources.FindObjectsOfTypeAll<GameObject>();
        var oldSelect = Selection.objects;
        Selection.objects = allGos;
        var transforms = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
        Selection.objects = oldSelect;
        foreach (var tr in transforms)
        {
            var com = tr.GetComponent<T>();
            if(com!=null)
            {
                result.Add(com);
            }
        }
        return result.ToArray();
    }
}